<template>
  <div class="">
    <el-form ref="valueMapper" :model="valueMapper" label-width="150px" size="mini">
      <el-form-item label="步骤名称" prop="name">
        <el-input v-model="valueMapper.name"/>
      </el-form-item>
      <el-form-item label="使用字段名" prop="field_to_use">
        <el-select v-model="valueMapper.field_to_use" placeholder="请选择" style="width:100%">
          <el-option
            v-for="item in fieldOptions"
            :key="item.name"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="目标字段名(空=覆盖)" prop="target_field">
        <el-input v-model="valueMapper.target_field"/>
      </el-form-item>
      <el-form-item label="不匹配时默认值" prop="non_match_default">
        <el-input v-model="valueMapper.non_match_default"/>
      </el-form-item>
      <div class="box" title="字段值" style="margin-top:20px;">
        <el-row>
          <el-col :span="24">
            <el-table v-loading="dataListLoading" :data="valueMapper.fields" border style="width: 100%;" size="mini" height="200">
              <el-table-column label="操作" width="80" :resizable="false">
                <template slot-scope="scope">
                  <div class="optionStyle">
                    <el-button
                      type="text"
                      size="mini"
                      @click="removeObj(scope.$index)"
                    >
                      移除
                    </el-button>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="source_value" label="源值">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.source_value" size="mini"/>
                </template>
              </el-table-column>
              <el-table-column prop="target_value" label="目标值">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.target_value" size="mini"/>
                </template>
              </el-table-column>
            </el-table>
            <el-row style="position: absolute; left: calc(50% + 20px); top: 100px;">
              <el-button icon="el-icon-sort" circle style="transform: rotate(90deg); " type="success" title="互换" @click="exchange"/>
            </el-row>
            <el-col :span="24">
              <el-row type="flex" justify="center" style="margin-top:10px;">
                <!-- :disabled="valueMapper.synoId" -->
                <el-button style="margin-top: 0; margin-left: 20px; width: 200px;" class="el-table-add-row" @click="addObj" icon="el-icon-plus"> 添加</el-button>
              </el-row>
            </el-col>
          </el-col>
        </el-row>
      </div>
    </el-form>
    <div class="el-dialog__footer">
      <span class="dialog-footer">
        <el-button
          icon="el-icon-back"
          @click="cancel"
        >取消
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-check"
          @click="handleSaveData()"
        >确定
        </el-button>
      </span>
    </div>
  </div>
</template>

<script>
/* eslint-disable new-cap */
import API from '../../../../../api/index'
import mxgraph from '../../../../../graph/VueMxGraphLoader'
import dictSelect from '../../../std/dict-select.vue'
import synonym from './synonym'
import xmlToFlinkJSON from '../../../../../utils/xmlToFlinkJson'
import httpRequest from '../../../../../utils/studioRequest'

const {
  mxUtils,
  mxCodec
} = mxgraph
export default {
  name: 'ValueMapper',
  components: {
    dictSelect,
    synonym
  },
  props: {
    name: String
  },
  data() {
    return {
      moduleUrl: 'std/syno/type/',
      graph: null,
      valueMapper: {
        type: 'ValueMapper',
        name: '',
        field_to_use: '',
        target_field: '',
        non_match_default: '0',
        fields: [],
        dictName: '',
        dictId: '',
        // 权威名称
        stdName: '',
        synoId: ''
      },
      temp: {
        type: 'ValueMapper',
        name: '',
        field_to_use: '',
        target_field: '',
        non_match_default: '0',
        fields: [],
        dictName: '',
        dictId: '',
        // 权威名称
        stdName: '',
        synoId: ''
      },
      fieldOptions: [],
      dataListLoading: false
    }
  },
  mounted() {

  },
  methods: {
    loadData(data) {
      if (data) {
        this.$forceUpdate()
        this.$deepCopy(this.valueMapper, data)
        // console.log(this.valueMapper)
        if (this.valueMapper.synoId && this.valueMapper.synoId !== 'null') {
          // console.log(this.valueMapper.stdName)
        }
        // if (this.valueMapper.dictId && this.valueMapper.dictId !== 'null') {
        //   this.$nextTick(() => {
        //     this.$refs.dictSelect.init(this.valueMapper.dictId)
        //   })
        // } else {
        //   this.$nextTick(() => {
        //     this.$refs.dictSelect.init()
        //   })
        // }
      }
    },
    // 保存表单数据
    handleSaveData() {
      if (this.valueMapper.name) {
        this.$emit('savePluginData', this.valueMapper)
      } else {
        this.$message({
          message: '步骤名称必填',
          type: 'warning'
        })
      }
    },
    setGraph(val) {
      this.graph = val
      this.getStreamField()
    },
    cancel() {
      this.$emit('cancel')
    },
    // 重置表单数据
    resetFormData(stepname) {
      this.$forceUpdate()
      this.$refs['valueMapper'].resetFields()
      this.$deepCopy(this.valueMapper, this.temp)
      this.valueMapper['name'] = stepname
    },
    async getStreamField() {
      const value = await this.getXml()
      await API.trans.flinkInputFields(value, { 'stepName': this.valueMapper.name }).then(res => {
        this.$set(this, 'fieldOptions', res.data.data.data.fields)
      })
    },
    getXml() {
      // this.saveTempPluginData(this.valueMapper)
      // const graph = this.graph
      // const enc = new mxCodec(mxUtils.createXmlDocument())
      // const node = enc.encode(graph.getModel())
      // const value = mxUtils.getPrettyXml(node)
      // return value
      this.saveTempPluginData(this.valueMapper)
      const graph = this.graph
      const enc = new mxCodec(mxUtils.createXmlDocument())
      const node = enc.encode(graph.getModel())
      const queryParJson = xmlToFlinkJSON.xmlToFlinkModels(node)
      queryParJson.models.model['step_name'] = this.valueMapper.name
      queryParJson.models.model['step_type'] = 'ValueMapper'
      return queryParJson
    },
    saveTempPluginData(formData) {
      this.$emit('saveTempPluginData', formData)
    },
    removeObj(index) {
      this.valueMapper.fields.splice(index, 1)
    },
    addObj() {
      this.valueMapper.fields.push({})
      this.$nextTick(() => {
        const container = this.$el.querySelector('.el-table__body-wrapper')
        container.scrollTop = container.scrollHeight
      })
    },
    currentChangeHandle(data, node) {
      if (!data) {
        this.valueMapper.dictName = ''
        this.valueMapper.dictId = ''
        this.valueMapper.fields = []
        return
      }
      const _that = this
      _that.valueMapper.synoId = ''
      _that.dataListLoading = true
      _that.valueMapper.dictName = data.dictName
      _that.valueMapper.dictId = data.id
      httpRequest({
        url: httpRequest.adornFlinkUrl(`/std/dict/type/${data.id}`),
        method: 'get'
      }).then(({ data }) => {
        if (data && data.code === 0) {
          _that.valueMapper.fields.length = 0
          for (var i = 0; i < data.dict.length; i++) {
            var row = {}
            row.source_value = data.dict[i].dictCode
            row.target_value = data.dict[i].dictName
            _that.valueMapper.fields.push(row)
          }
        }
        this.dataListLoading = false
      })
    },
    synonymClick(nodeList) {
      // 防止重复
      const map = {}
      for (const item of this.valueMapper.fields) {
        map[item.source_value] = true
      }
      for (const item of nodeList) {
        if (!map.hasOwnProperty(item.synoName)) {
          this.valueMapper.fields.push({ source_value: item.synoName, target_value: item.stdName })
        }
      }
    },
    exchange() {
      for (var i in this.valueMapper.fields) {
        const tmp = this.valueMapper.fields[i].source_value
        this.valueMapper.fields[i].source_value = this.valueMapper.fields[i].target_value
        this.valueMapper.fields[i].target_value = tmp
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">

.box{
  position:relative;
  border:1px solid #dcdfe6;
  padding:30px 5px 10px 5px;
}
.box::before{
  content:attr(title);
  position:absolute;
  top: 0%;
  left:10%;
  transform:translateX(-50%);
  -webkit-transform:translate(-50%,-50%);
  padding:0px 10px;
  background-color:#fff;
}
</style>
